<?php
require_once('../../../config.php');
require_once('../lib.php');


define('TYPE_ERRO','erro');
define('TYPE_EXIT','exit');
define('TYPE_MESSAGE','message');
define('TYPE_NO_MESSAGE','nomessage');
define('TYPE_ENTER','enter');

function chat_format_message_ajax($message, $courseid, $currentuser, $chat_lastrow=NULL) {
	static $users;     // Cache user lookups

	$output = new object();

	if ($message->system != 0){
		$output->type=$message->message;
		return $output;
	}

	$output->type=TYPE_MESSAGE;
	$output->to = -1;

	if (isset($users[$message->userid])) {
		$user = $users[$message->userid];
	} else if ($user = get_record('user', 'id', $message->userid, '','','','','id,picture,firstname,lastname')) {
		$users[$message->userid] = $user;
	}

	$output->from = $user->id;

	//Commands processing
	if(substr($message->message, 0, 1) == '/') {
		$command=explode(' ',$message->message);
		switch (array_shift($command)) {
			case "/to":
				$output->to=array_shift($command);
				$message->message=implode(" ", $command);
				break;
		}
	}
	$formated_msg=chat_format_message($message, $courseid, $currentuser, $chat_lastrow);

	$output->picture=$message->picture;
	$output->html=$formated_msg->html;
	$output->text=$formated_msg->text;

	if ($output->to == $currentuser->id){
		$user_to=get_record("user","id",$output->to);
		$message->message=get_string("sendprivatemsg","chat") . " " . $user_to->firstname . ":" . $message->message;
		if (!update_record('chat_messages', $message)) {
			error('Could not insert a chat message!');
		}
	}

	return $output;
}

function event_message($type, $event_str=''){
	$output = new object();
	$output->beep=false;
	$output->message=$event_str;
	$output->type=$type;
	return $output;
}


function no_message() {
	return event_message(TYPE_NO_MESSAGE);
}



function error_message($erro_str) {
	return event_message(TYPE_ERRO,$erro_str);

}

function execute_query_with_limit($query_str,$limit=1){
	global $db, $CFG;

	if (!$query_str){
		return false;
	}
	if (!$rs = $db->SelectLimit($query_str, 1)) {
		return false;
	}
	$result = rs_fetch_record($rs);
	rs_close($rs);
	return $result;
}

?>